function init(){
	// create filter object
	var fi = window.filter = new Filter();
	fi.parse(document.URL);

	// history state
	history.state = fi;
	window.onpopstate = function(e) {
		if (!e.state) return;
		var ajaxUrl = document.URL.replace(/\?.*/, '');
		window.filter.params = e.state;
		if (window.filter.params)
			ajaxUrl += '?'+window.filter.generateQueryString()
		updateContent(ajaxUrl);
	};
	afterAjaxUpdate();
}

function afterAjaxUpdate() {
	initAjaxUpdate();
	initLazyLoading();
	initQuickEdit();
	window.scrollTo(0, 300);
}

/**
 * Load ajax when click filter
 *
 */
function initAjaxUpdate() {
	var fi = window.filter;
	
	$('select.ajaxUpdate, input.ajaxUpdate').on('change.ajaxUpdate', function(){
		// get input value
		var param = this.name.replace('[]', '');
		var value = Form.getInputValue(this.name);
		if (value instanceof Array)
			value = value.join('_');
		fi.setParam(param, value);

		// build ajax url
		var ajaxUrl = document.URL.replace(/\?.*/, '')+'?'+fi.generateQueryString();
		history.pushState(fi.params, '', ajaxUrl);
		updateContent(ajaxUrl);
	});
	
	$('a.ajaxUpdate').on('click.ajaxUpdate', function(e){
		e.preventDefault();

		var ajaxUrl = this.href;
		fi.parse(ajaxUrl);
		history.pushState(fi.params, '', ajaxUrl);
		updateContent(ajaxUrl);
	});
}

/*
 * perform ajax post and update page content
 */
function updateContent(ajaxUrl) {
	$('#loading').show();
	var options = {
		type: 'GET',
		url: ajaxUrl,
		success: function(data,status) {
			var ajaxContent = $(data);
			$('#sidebar').replaceWith(ajaxContent.find('#sidebar'));
			$('#col-main').replaceWith(ajaxContent.find('#col-main'));

			afterAjaxUpdate();
			$('#loading').hide();
		},
		error: function(XHR, textStatus, errorThrown) {
		}
	};
	$.ajax(options);
}

/*
 * Make image lazy loading
 */
function initLazyLoading() {
	$(".post img").not(".post iframe img").unveil(150);
}

/*
 * Show post edit dialog when click edit button
 */
function initQuickEdit() {
	$(".edit-btn").fancybox({
		type		: 'ajax',
		width		: '80%',
		height		: '80%',
		autoSize	: false,
	});
}

/*
 * Filter class
 */
function Filter () {
    this.params = {};

    this.generateQueryString = function() {
		if (!this.params) return '';
		return $.param(this.params);
    };
	
    this.parse = function(url) {
		this.params = {};
		
		if (url.getQueryString()=='')
			return;

		var self = this;
		var keyValuePairs = url.getQueryString().split('&');
		keyValuePairs.forEach(function(keyValuePair) {
			keyValuePair = keyValuePair.split('=');
			if (keyValuePair[0]!='')
				self.params[keyValuePair[0]] = keyValuePair[1] || '';
		});
    };

    this.setParam = function(name, value) {
		if (value==null) {
			if (name in this.params) delete this.params[name];
		} else {
			this.params[name] = value;
		}
    };
}

/*
 * Form helper
 */
var Form = {
	/**
	 * Get input value by name
	 *
	 * @return array|string|null
	 */
	getInputValue: function(name) {
		var inps = $('[name="'+name+'"]');
		if (inps.size()==1) { // textbox, textarea, select box
			return inps.val();	
		} else if (inps.size()>1) {	
			if ($(inps[0]).is(':radio'))	// radio
				return inps.filter(':checked').val();
			return this.getCheckboxValue(name); // maybe it is checkbox
		}
		return null;
	},

	/**
	 * Get selected values of checkbox
	 *
	 * @return array|null
	 */
	getCheckboxValue: function(name) {
		var values = [];
		$('input[name="'+name+'"]:checked').each(function() {
			values.push(this.value);
		});
		if (!values.length) values = null;
		return values;
	},
}

/*
 * Extend string class
 */
String.prototype.getQueryString = function() {
	var parts = this.split('?');
	if (typeof parts[1]=='undefined')
		return '';
	return parts[1];
}

